﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Threading;
using MbWsClient.ServiceClasses;
using MbWsClient.Service.Enums;

namespace MbWsClient.Classes
{
    public class ItemRepository
    {
        #region Private Members

        private static Dictionary<Guid, Item> _items = new Dictionary<Guid, Item>();
        private static readonly object lockObj = new object();
        private static List<BasicItem> _itemStack = new List<BasicItem>();

        #endregion

        public static CollectionItem StartupFolders()
        {
            string fileName = string.Format("StartupFolder.{0}*", AppSettings.ServerName);
            var files = AppSettings.ItemCacheDir.GetFiles(fileName);
            bool hasCached = false;
            CollectionItem collItem = null;
            if (files.Length == 1)
            {
                string[] split = files[0].Name.Split('.');
                if (split.Length == 2)
                {
                    Guid guid = new Guid(split[1]);
                    BasicItem item = new BasicItem();
                    item.Id = guid;
                    item.Type = MediaTypes.Folder;
                    try
                    {
                        collItem = (CollectionItem)GetItem(item);
                        hasCached = true;
                    }
                    catch { }
                }
            }

            if (!hasCached)
            {
                var folders = AppSettings.MbService.GetStartUpFolders();
                collItem = new CollectionItem(folders);
                collItem.Save();
                File.Create(Path.Combine(AppSettings.ItemCacheDir.FullName, "StartupFolder." + folders.Id));
            }
            _itemStack = new List<BasicItem> { collItem };
            return collItem;

        }

        public static Item GetNextItem(BasicItem item)
        {
            _itemStack.Add(item);
            return GetItem(item);
        }

        public static Item GetPreviousItem()
        {
            Item retVal = null;
            int count = _itemStack.Count;
            if (count > 1)
            {
                retVal = GetItem(_itemStack[count - 2]);
                _itemStack.RemoveAt(count - 1);
            }
            else
            {
                retVal = StartupFolders();
            }

            return retVal;
        }

        public static Item GetItem(BasicItem item)
        {
            lock (lockObj)
            {
                if (_items.ContainsKey(item.Id))
                {
                    return _items[item.Id];
                }
                else
                {
                    if (item.Type == MediaTypes.Folder ||
                        item.Type == MediaTypes.Season ||
                        item.Type == MediaTypes.Series)
                    {
                        CollectionItem collectionItem = null;

                        FileInfo[] files = AppSettings.ItemCacheDir.GetFiles(item.Id + "*");
                        if (files.Length == 1)
                        {
                            collectionItem = CollectionItem.Parse(files[0]);
                        }
                        else
                        {
                            BasicCollectionItem collection = AppSettings.MbService.GetCollection(item.Id);
                            collectionItem = new CollectionItem(collection);
                            ThreadPool.QueueUserWorkItem(o => { collectionItem.Save(); });
                        }
                        _items.Add(collectionItem.Id, collectionItem);
                        return collectionItem;
                    }
                    else
                    {
                        Item newItem = new Item(item);
                        _items.Add(item.Id, newItem);
                        return newItem;
                    }
                }
            }
        }

        public static void ClearCache(BasicItem item)
        {
            FileInfo[] files = AppSettings.ItemCacheDir.GetFiles(item.Id + "*");
            _items.Remove(item.Id);
            foreach (FileInfo file in files)
                File.Delete(file.FullName);
        }

        public static void ClearEntireCache()
        {
            Directory.Delete(AppSettings.ItemCacheDir.FullName, true);
            AppSettings.ItemCacheDir.EnsureDirectoryExistance();
        }
    }
}
